package com.heeexy.example.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.IoUtils;
import com.alibaba.fastjson.JSONObject;
import com.heeexy.example.dao.TeacherDao;
import com.heeexy.example.dao.UserDao;
import com.heeexy.example.dto.TeacherInfo;
import com.heeexy.example.listener.ExeclDataListener;
import com.heeexy.example.util.CommonUtil;
import com.heeexy.example.util.constants.ErrorEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author: MyPC
 * @description: 老师Server层
 * @date: 2022/03/26 13:46
 */
@Slf4j
@Service
public class TeacherService {
    @Autowired
    public void setTeacherDao(TeacherDao teacherDao) {
        this.teacherDao = teacherDao;
    }

    private TeacherDao teacherDao;

    @Autowired
    private UserDao userDao;


    public JSONObject listTeacher() {
        List<JSONObject> list = teacherDao.listTeacher();
        return CommonUtil.successPage(list);
    }

    /**
     * 导入教师xls
     * @param file
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject saveTeacherXls(MultipartFile file) {
        try{
            //获取原始文件名
            String oldFileName = file.getOriginalFilename();
            //获取文件后缀名
            String extension = "."+ FilenameUtils.getExtension(oldFileName);
            //生成缓存名
            String  newFileName = new SimpleDateFormat("yyyyMMddHHmmss")+ UUID.randomUUID().toString().replace("-","")+extension;
            //获取文件格式 ：application/vnd.ms-excel
            String type = file.getContentType();
            //判断文件类型，是否包含："xls"
//            if(!type.startsWith("xls")){
//                return CommonUtil.errorJson(ErrorEnum.E_415);
//            }
            //设置文件存放路径
            String realPath=ResourceUtils.getURL("classpath:").getPath()+"/static/files";
            //根据日期生成目录
            File dateDir =new File(realPath+"/"+new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
            if (!dateDir.exists()) {
                dateDir.mkdirs();
            }
            String path =dateDir.getPath();
            //将文件信息放入数据库
            EasyExcel.read(file.getInputStream(), TeacherInfo.class, new ExeclDataListener(teacherDao,userDao)).sheet().doRead();
            //处理文件上传
            file.transferTo(new File(dateDir,newFileName));
        }catch (IOException e){
            log.error("imPortXls()方法IOException报错:"+e.getMessage());
            return CommonUtil.errorJson(ErrorEnum.E_400);
        }
        return CommonUtil.successJson();
    }

    /**
     * 导出教师xls
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void WriteTeacherXls(HttpServletResponse response) {
        try{
            String realPath=ResourceUtils.getURL("classpath:").getPath()+"/static/files";
            //根据日期生成目录
            File dateDir =new File(realPath+"/"+new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
            if (!dateDir.exists()) {
                dateDir.mkdirs();
            }
            //生成缓存名
            String  newFileName = new SimpleDateFormat("yyyyMMddHHmmss")+ UUID.randomUUID().toString().replace("-","")+".xls";
            List<JSONObject> teacherList = teacherDao.listTeacher();
            EasyExcel.write(new File(dateDir,newFileName), TeacherInfo.class).sheet("教师团队").doWrite(teacherList);
            FileInputStream inputStream = new FileInputStream(new File(dateDir,newFileName));
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode("教师名单","UTF-8")+".xls");

            ServletOutputStream outputStream =response.getOutputStream();
            IoUtils.copy(inputStream,outputStream);
            inputStream.close();
            outputStream.close();
        }catch (FileNotFoundException e){
            log.error("创建文件路径失败："+e.getMessage());
        } catch (IOException e) {
            log.error("ServletOutputStream获取流失败："+e.getMessage());
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public JSONObject saveTeacherInfo(JSONObject jsonObject) {
        //判断用户是否存在
        int exist = 0;
        if (exist > 0) {
            return CommonUtil.errorJson(ErrorEnum.E_10009);
        }
        teacherDao.insertTeacher(jsonObject);
        return CommonUtil.successJson();
    }

}
